package com.frank.activedatabus.broadcast;

import com.frank.activedatabus.Core.Observer;
import ohos.event.commonevent.CommonEventSubscriber;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @version 1.0.1
 * @description:
 * @program: Gallery
 * @Author xiaozhijun
 * @Date 2020/12/24 17:04
 */
public class BroadCastCacheManage {

    private static final String TAG = "EventSubjectCacheManage";

    //用于存储公共事件的所有订阅
    private ConcurrentHashMap<String, ConcurrentHashMap<Observer, CommonEventSubscriber>> subscriberHashMap = new ConcurrentHashMap<>();

    /**
     * 添加到订阅缓存中
     *
     * @param listener   回调接口
     * @param action     订阅主题
     * @param subscriber 公共事件订阅者
     */
    protected synchronized void add(Observer listener, String action, CommonEventSubscriber subscriber) {
//        LogUtils.i(TAG, "add subscriber");
        if (!subscriberHashMap.containsKey(action) || subscriberHashMap.get(action) == null) {
            ConcurrentHashMap<Observer, CommonEventSubscriber> item = new ConcurrentHashMap();
            item.put(listener, subscriber);
            subscriberHashMap.put(action, item);
        } else {
            ConcurrentHashMap<Observer, CommonEventSubscriber> items = subscriberHashMap.get(action);
            if (!items.containsKey(listener) || items.get(listener) == null) {
                items.put(listener, subscriber);
            }
        }

    }

    /**
     * 从订阅缓存中移除
     *
     * @param listener 回调接口
     * @param action   订阅主题
     * @return 需要移除的订阅者
     */
    protected synchronized CommonEventSubscriber remove(Observer listener, String action) {
        CommonEventSubscriber result = null;
//        LogUtils.i(TAG, "remove subscriber" + action);
        if (subscriberHashMap.containsKey(action) && subscriberHashMap.get(action) != null) {
            ConcurrentHashMap<Observer, CommonEventSubscriber> items = subscriberHashMap.get(action);
            if (items.containsKey(listener)) {
                result = items.remove(listener);
            }
        }
        return result;
    }

    /**
     * 根据订阅主题 以及回调接口 检测在缓存中是否存在对应的订阅者
     *
     * @param listener 接口回调
     * @param action   订阅主题
     * @return
     */
    protected synchronized boolean contains(Observer listener, String action) {
        boolean isContain = false;
        if (subscriberHashMap.containsKey(action) && subscriberHashMap.get(action) != null) {
            ConcurrentHashMap<Observer, CommonEventSubscriber> items = subscriberHashMap.get(action);
            if (items.containsKey(listener)) {
                isContain = true;
            }
        }
        return isContain;
    }

}
